<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span class="role-span project-title">{{ profile.name }}</span>
        <div class="box-card-btn">
          <el-button
            type="success"
            class="refresh-btn"
            :loading="profileLoading"
            @click="refreshProfile"
          >
            刷新项目信息
          </el-button>
          <el-button
            type="primary"
            @click="applyProject"
            v-if="profile.bidStatus === 'INIT'"
            :disabled="!supplierProfile.id"
          >
            报名
          </el-button>

          <!-- 未授标, 授标了应该这个页面也看不到了 -->
          <div v-if="profile.status != 'AWARD'">
            <vue-countdown-timer
              @end_callback="entryTimeEnd"
              :start-time="Date.now()"
              :end-time="profile.entryTime"
              :interval="1000"
              :end-label="'距离报名时间结束还有'"
              label-position="begin"
              :end-text="'报名已截止,等待报价'"
              :day-txt="'天'"
              :hour-txt="'小时'"
              :minutes-txt="'分钟'"
              :seconds-txt="'秒'"
              class="timer"
              v-if="!entryEnd"
            ></vue-countdown-timer>
            <vue-countdown-timer
              :start-time="Date.now()"
              :end-time="profile.openTime"
              :interval="1000"
              :end-label="'距离开标时间还有'"
              label-position="begin"
              :end-text="'已停止报价,等待开标'"
              :day-txt="'天'"
              :hour-txt="'小时'"
              :minutes-txt="'分钟'"
              :seconds-txt="'秒'"
              class="timer"
              v-else
            ></vue-countdown-timer>
          </div>
        </div>
      </div>
      <profile-table :profile="profile"></profile-table>
    </el-card>

    <el-card shadow="never">
      <div slot="header" class="clearfix">
        <span class="role-span">
          报价清单
        </span>
        <div class="box-card-btn">
          <el-button type="primary" @click="expandAllPlan" v-if="!planExpanded">
            展开所有报价清单
          </el-button>
          <el-button type="warning" @click="expandAllPlan" v-else>
            收起所有报价清单
          </el-button>

          <el-button type="success" @click="offerPrice" :disabled="!supplierHasPassed">
            提交报价
          </el-button>
        </div>
      </div>

      <plan-offer-list
        ref="planOfferList"
        v-if="profile.projectPlans"
        :project-plans="profile.projectPlans"
        :offer-list="offerList"
        :disabled="!supplierHasPassed"
      ></plan-offer-list>
    </el-card>
    <!-- 流转表格 -->
    <clar :status-list="statusList"></clar>
  </div>
</template>

<script>
  import * as ProjectRequest from '@/api/project';
  import * as SupplierRequest from '@/api/supplier';
  import { resultFormatter } from '@/utils';
  import PlanOfferList from './planOfferList';
  import ProfileTable from './profileTable';
  import Clar from './clar';

  export default {
    name: 'ProjectSupplierProcess',

    data() {
      return {
        pid: '',
        supplierProfile: {},
        profile: {},
        profileLoading: false,
        entryEnd: false,
        planExpanded: false,
        offerList: [],
        statusList: [],
      };
    },
    components: {
      PlanOfferList,
      ProfileTable,
      Clar,
    },
    watch: {
      $route() {
        this.init();
      },
    },
    computed: {
      supplierHasPassed() {
        return this.profile.bidStatus === 'PASS' && this.profile.status === 'INIT';
      },
    },
    mounted() {
      this.init();
    },
    methods: {
      init() {
        const { pid } = this.$route.query;
        if (pid) {
          this.pid = pid;
          this.getProjectProfile();
          this.getSupplierProfile();
        } else {
          this.$message.error('项目不存在, 或者无访问权限');
          this.$EventBus.$emit('closeCurrentPage');
        }
      },
      /**
       * 获取项目状态
       */
      getProjectStatus() {
        ProjectRequest.getProjectStatus({
          projectId: this.pid,
        }).then((res) => {
          // 这里还是反转一下看着舒服些
          this.statusList = [...res.content].reverse();
        });
      },
      /**
       * 获取供应商的信息
       */
      getSupplierProfile() {
        SupplierRequest.getProfile().then((res) => {
          if (res) {
            this.supplierProfile = { ...res };
          }
        });
      },
      getProjectProfile() {
        if (this.profileLoading) return;
        this.profileLoading = true;
        return ProjectRequest.getSupplierProject({
          projectId: this.pid,
        })
          .then((res) => {
            // 授标检查
            if (res.status === 'AWARD') {
              this.$EventBus.$emit('closeCurrentPage');
              this.$message.error('项目已经授标完毕, 无法查看!');
              return;
            }

            this.profile = {
              ...res,
              projectPlans: resultFormatter(res.projectPlans),
            };
            this.offerList = res.supplierPlans;
            this.entryTimeEnd();
            this.getProjectStatus();
          })
          .finally(() => {
            this.profileLoading = false;
          });
      },
      refreshProfile() {
        this.getProjectProfile().then(() => {
          this.$message.success('刷新项目信息成功!');
        });
      },
      applyProject() {
        ProjectRequest.applyProject({
          projectId: this.profile.id,
          supplierId: this.supplierProfile.id,
        }).then((res) => {
          this.$message.success('提交报名成功,请等待审核!');
          this.getProjectProfile();
        });
      },
      entryTimeEnd() {
        this.entryEnd = this.profile.entryTime - Date.now() < 1000;
      },
      expandAllPlan() {
        this.$EventBus.$emit('expandAllPlan', this.planExpanded);
        this.planExpanded = !this.planExpanded;
      },
      offerPrice() {
        // this.$refs['planOfferList']
        //   .validateForm()
        //   .then((res) => {
        //     console.log(res);
        //   })
        //   .catch((err) => {
        //     console.log(err);
        //   });
        // return;
        // this.$refs['planOfferList'].$refs['offer-form'].validate((valid) => {
        //   console.log(valid);
        // });
        // 这里还是要做个验证判断,是否都填了
        this.$confirm('确认提交现有报价?', '提交报价').then(() => {
          const plans = this.$refs['planOfferList'].localOfferList.map((offer) => {
            return {
              ...offer,
              detail: JSON.stringify(offer.detail),
            };
          });

          ProjectRequest.offerPrice({
            plans,
            projectId: this.pid,
          }).then(() => {
            this.$message.success('报价成功!请等待开标结果');
          });
        });
      },
    },
  };
</script>

<style lang="scss" scoped>
  .timer {
    font-size: 12px;
    color: red;
    font-weight: bolder;

    /deep/ i {
      font-style: normal;
    }
  }

  .project-title {
    font-size: 26px;
    font-weight: bolder;
    vertical-align: middle;
  }

  .box-card-btn {
    vertical-align: bottom;
    display: flex;
    align-items: center;

    .refresh-btn {
      margin-right: 10px;
    }
  }
</style>
